<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="search">
        <el-form-item>
          <el-input v-model="search.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.list"
              highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="password" label="密码" width="120" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180" sortable>
      </el-table-column>
      <el-table-column prop="headImage" label="头像" width="180" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="120" sortable>
      </el-table-column>
      <el-table-column prop="department.id" label="隶属部门" width="120" sortable>
      </el-table-column>

      <el-table-column prop="state" label="状态" width="120" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: #11b95c">正常</span>
          <span v-else style="color: red">禁用</span>
        </template>
      </el-table-column>


      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--
          @size-change: 当涉及的每页条数发生改变的时候触发的函数
          @current-change: 页数发生改变
          :current-page 当前第几页
          :page-sizes="[3, 5, 10, 20]" : 设定每页的条数
          :page-size="this.search.pageSize" 每页条数
      -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.search.currentPage"
          :page-sizes="[3, 5, 10, 20]"
          :page-size="this.search.pageSize"
          style="float: right"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
    </el-col>

    <!--编辑/新增界面-->
    <el-dialog title="编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="saveForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <!--下拉选项
            :key=""  //唯一标识
            :label 选择之后展示到选择框中的值
            :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
               必须要写  value-key="id"
          -->
          <el-select v-model="saveForm.manager" clearable value-key="id" placeholder="请选择">
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-input v-model="saveForm.state" auto-complete="off"></el-input>
        </el-form-item>




      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>

<script>

export default {
  data() {
    return {
      search: {
        keyword: '',
        pageSize:10,
        currentPage:1
      },
      pageInfo:{
        list: [],
        total: 0
      },

      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false,//编辑界面是否显示
      editLoading: false,
      saveFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        username: '',
        password:'',
        department:{
          id:null,
          name:""
        },
        // parent:{
        //   id:null,
        //   name:""
        // },
        age:'',
        email:'',

      },
      // //定义部门主管数组
      // employees:[],
      // // 定义父级部门树
      // deptTree:[],
    }
  },
  methods: {
    // 获取父部门信息
    getDeptTree(){
      this.$http.get("/employee")
          .then(res => {

            var data = res.data;
            if(data.success){

              this.deptTree = data.data
            }
          }).catch(res=>{

      })
    },
    // 获取部门主管信息
    getEmployees(){
      this.$http.get("/employee")
          .then(res => {

            var data = res.data;
            if(data.success){

              this.employees = data.data
            }
          }).catch(res=>{

      })
    },
    // 点击查询
    getSearch(){
      this.search.currentPage = 1;
      this.getDepartments()
    },
    handleSizeChange(val){
      this.search.pageSize = val
      this.getDepartments();
    },

    handleCurrentChange(val) {
      this.search.currentPage = val;
      this.getDepartments();
    },
    //获取部门列表
    getDepartments() {

      // 发送请求 axios请求
      this.$http.post("/employee",this.search)
          .then(res => {
            console.log(res)
            var data = res.data;
            if(data.success){
              // this.pageInfo.list = data.data.list
              // this.pageInfo.total = data.data.total
              this.pageInfo = data.data
            }
          }).catch(res=>{

      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('他会消失很长一段时间', '你确定？', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();

        this.$http.delete("/employee/"+row.id)
            .then(res=>{
              res = res.data;
              if(res.success){
                this.$message({ message: '你说了算', type: 'success' });
                this.search.currentPage = 1
                this.getDepartments()
                this.listLoading = false;
              }
            }).catch(res=>{

        })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.saveFormVisible = true;

      this.saveForm = Object.assign({}, row);
      if (!row.manager){
        this.saveForm.manager={id:null,username:''}
      }
      if (!row.parent){
        this.saveForm.parent={id:null,name:''}
      }else{
        // 父部门 不为空 获取path
        var split = row.path.split("/");
        var path = [];
        for (let i = 1; i < split.length-1; i++) {
          // push往数组中添加 pop是移除
          path.push(Number.parseInt(split[i]))
          this.saveForm.parent = path
        }
      }
      this.getEmployees()
      this.getDeptTree();


    },
    //显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        name: '',
        path:'',
        manager:{
          id:null,
          username:""
        },
        parent:{
          id:null,
          name:""
        },
        intro:'',
        state:'',
      };
      this.getEmployees()
      this.getDeptTree();
    },
    //编辑
    editSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('不再检查一下？', '先等等', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            if(this.saveForm.parent.length>=0){
              if(this.saveForm.parent.length==0 ){
                this.saveForm.parent = {
                  id:null
                }
              }else{
                this.saveForm.parent = {
                  id:this.saveForm.parent[this.saveForm.parent.length-1]
                }
              }
            }
            this.$http.put("/employee",this.saveForm)
                .then(res=>{
                  res = res.data
                  if (res.success){
                    this.$message({ message: '你说了算', type: 'success' });
                    this.editLoading = false;
                    this.search.currentPage = 1
                    this.getDepartments()
                    this.saveFormVisible = false;
                  }
                })
                .catch(res=>{})
          });
        }
      });
    },
    //新增
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('不再检查一下？', '先等等', {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.addForm);
            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            addUser(para).then((res) => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: '你说了算',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getUsers();
            });
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('我说真的，这太残酷了', '你确定？', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/employee",ids)
            .then(res => {
              console.log(res)
              var data = res.data;
              if(data.success){
                this.$message({ message: '你说了算', type: 'success' });
                this.listLoading = false
                this.getSearch();
              }
            }).catch(res=>{

        })
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getDepartments();
  }
}

</script>

<style scoped>

</style>